// @ts-nocheck
import React, { FC, useState, useEffect, useMemo } from "react";
import {
  NavBar,
  Button,
  Form,
  Input,
  Cascader,
  TextArea,
  ImageUploader,
  Toast,
} from "antd-mobile";
import { Spin } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { CascaderOption } from "antd-mobile/es/components/cascader";
import { getListToOptions } from "@/utils/tools";
import { IAddressItem } from "@/components/MapComponent";
import  {HandOk} from "@/components";
// service
import {
  IEventList,
  putServiceEventReportByFromData,
  upLoadImage,
  serviceItem
} from "./service";
import { getCurrentUser } from "@/utils/authority";
// style
import "./index.less";
interface IFormState {
  title: string;
  type: string[];
  address: string;
  addressDetailedUser: string;
  content: string;
}

interface IStartFormState {
  questiontitle: string;
  eventType: string;
  hadress: string; //位置
  detailedAddress: string; //详细位置
  desc: string; //描述
  longitude: number; //经度
  latitude: number; //纬度
  discoveryTime: string;
  eventNo: string; //事件编号
  // selfDisposal: "confirmDisposal" | "vetoDisposal";//是否自行处置
  fileFront: string[];
  // fileBack:string[];
}

function CommunityServiceReport() {
  const location = useLocation();
  // 当前服务上报类型
  const [eventReportType, setEventReportType] = useState()
  const userId = getCurrentUser()?.data?.user_id;
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [ImageList, setImageList] = useState<{ url: string; name: string }[]>([]);
  const [eventList, setEventList] = useState<CascaderOption[]>([]);
  const [addressItem, setAddressItem] = useState<IAddressItem | {}>({});
  const [users, setUsers] = useState();
  const [loaing, setLoaing] = useState(false);
  const [handOk, setHandOk] = useState(false)
  useEffect(() => {
    let type = location?.search?.slice(1)
    switch (type) {
      case "convenienceService":
        setEventReportType("家政便民")
        break;
      case "propertyRepair":
        setEventReportType("物业服务")
        break;
      case "communityMeal":
        setEventReportType("社区助餐")
        break;
      case "healthService":
        setEventReportType("健康服务")
        break;
      default:
        break;
    }
  }, [location])

  useEffect(() => {
    getEventTypeList(eventReportType);
  }, [eventReportType])
  
  const onFinish = async (values: IFormState) => {
    if (eventReportType) {
      const attachList: string[] = ImageList.map((item) => {
        return item.url;
      });
      setLoaing(true);
      const formCommitData: IStartFormState = {
        questiontitle: eventReportType,
        eventType: values.serviceType[values.serviceType.length - 1],//服务项目
        phone: values.phone,//联系电话   
        hadress: values.address,//发生地址
        desc: values.content,//服务描述
        longitude: addressItem.longitude,//服务地址经纬度
        latitude: addressItem.latitude,
        fileFront: attachList,//附件
      };
      try {
        const parma = formCommitData;
        const { success } = await putServiceEventReportByFromData(parma);
        if (!success) {
          Toast.show({
            icon: "fail",
            content: "上报失败",
          });
          setLoaing(false);
          setHandOk(false)
          return;
        }
        if (success) {
          setLoaing(false);
          Toast.show({
            icon: "success",
            content: "上报成功",
          });
          setHandOk(true)
          // navigate("/");
        }
      } catch (err) {
        console.error(err);
      }
    }
  };



  const handleMapOnFocous = () => {
    const formItem = form.getFieldsValue();
    localStorage.setItem("herf", "");
    localStorage.setItem("form", JSON.stringify(formItem));
    navigate(`/communityServiceReport/location?local=communityServiceReport?${location?.search?.slice(1)}`);
  };

  const getEventOptions = (x: IEventList) => {
    const obj: CascaderOption = {
      label: x.categoryCompleteName,
      value: x.categoryCompleteName,
    };
    if (x?.categoryChild) {
      obj["children"] = getListToOptions(x.categoryChild, getEventOptions);
    }
    return obj;
  };

  const getEventTypeList = async (eventReportType: string) => {
    if (eventReportType) {
      try {
        const { data, code, msg } = await serviceItem(eventReportType);
        if (code === 200) {
          const arr = data?.map(item => {
            return {
              label: item,
              value: item
            }
          })
          setEventList(arr)
        }
      } catch (err) {
        console.error(err);
      }
    }
  };

  async function mockUpload(file: File) {
    try {
      const { data } = await upLoadImage({ file: file });
      if (data?.code === 200) {
        Toast.show({
          icon: "success",
          content: "上传成功",
        });
      
        const url = data.data.length && data.data[0].link;
        const name = data.data.length && data.data[0].name;
        return {
          url,
          name,
        };
      } else {
        Toast.show({
          icon: "fail",
          content: "上传失败,该文件类型被限制上传",
        });
        return {
          url: "",
        };
      }
    } catch (err) {
      Toast.show({
        icon: "fail",
        content: "上传失败",
      });
      return {
        url: "",
      };
    }
  }

  useEffect(() => {
    const formItem = JSON.parse(
      localStorage.getItem("form") || JSON.stringify("")
    );
    form.setFieldsValue(formItem);

    const addressItems = JSON.parse(
      localStorage.getItem("address") || JSON.stringify({})
    );
    console.log(addressItems);
    const users = JSON.parse(
      localStorage.getItem("users") || JSON.stringify({})
    );
    setUsers(users);
    setAddressItem(addressItems);
    return () => {
      localStorage.removeItem("form");
      localStorage.removeItem("address");
      form.resetFields();
    };
  }, []);

  const Basic = useMemo(() => {
    return (
      <div>
        <div className="figImg">多添加图片，能更清晰的表明事件地点</div>
        <ImageUploader
          value={ImageList}
          maxCount={3}
          showUpload={ImageList.length < 3}
          onChange={setImageList}
          upload={mockUpload}
          multiple={false}
          // maxCount={0}
          capture={true}
        />
      </div>
    );
  }, [ImageList]);

  return (
    handOk ? <HandOk title="我们将尽快与您联系" header={eventReportType}/> 
    : 
    <Spin tip="提交中..." spinning={loaing}>
     <div className="reportcontent">
        <div>
          <NavBar
            onBack={() => navigate(-1)}
          // right={

          // }
          >
            <div className="commontitle">{eventReportType}</div>
          </NavBar>
        </div>

        <div className="eventFrom">
          <Form form={form} onFinish={onFinish}
            initialValues={{
              phone: users?.account
            }}
          >
            <Form.Item
              name="serviceType"
              label="服务项目"
              trigger="onConfirm"
              onClick={() => {
                setVisible(true);
              }}
              rules={[{ required: true, message: "必填项" }]}
            >
              <Cascader
                options={eventList}
                visible={visible}
                onClose={() => {
                  setVisible(false);
                }}
              >
                {(items) => {
                  if (items.every((item) => item === null)) {
                    return <div className="colour">点击选择服务项目</div>;
                  } else {
                    return items[items.length - 1]?.label;
                  }
                }}
              </Cascader>
            </Form.Item>
            <Form.Item
              name="phone"
              label="联系电话"
              rules={[{ required: true, message: "必填项" }]}
            >
              {/*  ！！！！写死原因：无法获取，魅力广安用户体系 */}
              <Input placeholder="请输入联系电话" />
            </Form.Item>
            <Form.Item
              name="address"
              label="服务地址"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入服务地址" onFocus={handleMapOnFocous} />
            </Form.Item>
            {/* <Form.Item name="addressDetailedUser" label="详细地址">
              <Input placeholder="请输入详细地址" />
            </Form.Item> */}
            <Form.Item
              name="content"
              label="服务描述"
              className="eventContent"
              rules={[{ required: true, message: "必填项" }]}
            >
              <TextArea placeholder="请输入服务描述" rows={4} />
            </Form.Item>
            <Form.Item
              label="照片"
              rules={[{ required: true, message: "必填项" }]}
              className="BasicBox"
            >
              {Basic}
            </Form.Item>
          </Form>
          <div className="bottomButton">
            <Button
              onClick={(e) => {
                if (!loaing) {
                  e.preventDefault();
                  form.submit();
                  
                }
              }}
              type="submit"
              className="reportbtn "
              style={{ fontSize: "1.5rem" }}
            >
              {loaing ? "提交中" : "提交"}
            </Button>
          </div>

        </div>

      </div>
    </Spin>
  );
}

export default CommunityServiceReport;
